<template>
  <div class="permission">
    <el-card>
      <div class="btnbox">
        <el-button @click="openAdd(1, 0)" type="primary" size="mini">
          <i class="el-icon-edit"></i>添加菜单
        </el-button>
        <el-table :data="perList" row-key="id">
          <el-table-column label="菜单名称" prop="name"></el-table-column>
          <el-table-column label="权限标识" prop="code"></el-table-column>
          <el-table-column label="描述" prop="description"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <el-button @click="openAdd(2, row.id)" v-if="row.type === 1" type="text">
                添加权限点
              </el-button>
              <el-button type="text">查看 api 权限</el-button>
              <el-button @click="openEdit(row.id)" type="text">查看</el-button>
              <el-button @click="del(row.id)" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <mypanel
      ref="mypanel"
      :showDialog.sync="showDialog"
      @updateData="getAllPer"
    ></mypanel>
  </div>
</template>

<script>
import { getAllPerApi, delPerApi } from '@/api/permission'
export default {
  data () {
    return {
      // 权限列表
      perList: [],
      // 面板的显示与隐藏
      showDialog: false
    }
  },
  methods: {
    // 打开新新增面板
    openAdd (type, pid) {
      this.showDialog = true
      this.$refs.mypanel.getData(type, pid)
    },
    // 打开编辑面板
    openEdit (id) {
      this.showDialog = true
      // 调用子组件中的获取数据方法
      this.$refs.mypanel.getPerDetail(id)
    },
    async del (id) {
      try {
        // 询问是否删除
        await this.$confirm('是否删除数据', '提示')
        // 调用删除的接口
        await delPerApi(id)
        // 提示删除成功
        this.$message.success('删除成功')
        // 更新数据
        this.getAllPer()
      } catch {}
    },
    // 得到所有的权限点数据
    async getAllPer () {
      const res = await getAllPerApi()
      this.perList = this.trunData(res.data, '0')
    },
    // 定义一个转换树状结构数据的方法
    trunData (arr, pid) {
      const res = []
      arr.forEach(item => {
        if (item.pid === pid) {
          const son = this.trunData(arr, item.id)
          if (son.length > 0) {
            item.children = son
          }
          res.push(item)
        }
      })
      return res
    }
  },
  created () {
    this.getAllPer()
  },
  components: {
    mypanel: () => import('./components/panel.vue')
  }
}
</script>

<style lang="scss">
.permission {
  margin: 20px;
  .btnbox {
    text-align: right;
  }
}
</style>
